import React, { useEffect } from 'react';

function ajax(url) {
  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    xhr.send();
  });
}

function* model() {
  const { data: user } = yield ajax('http://localhost:3001/api/userData');
  console.log(user);

  const { data: post } = yield ajax('http://localhost:3001/api/postData');
  console.log(post);
}

function main() {
  const generator = model();
  const result = generator.next();
  const { value: userAction } = result;

  userAction.then(user => {
    const { value: postAction } = generator.next(user);

    postAction.then(post => {
      generator.next(post);
    });
  });
}

export default function Useage() {
  useEffect(main, []);

  return (
    <div>
      <p>Promise 用例</p>
    </div>
  );
}
